package com.clss.emergencycall.base;

import android.annotation.TargetApi;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.clss.emergencycall.utils.Lg;
import com.clss.webrtclibrary.ConfigAndUtils;
import com.clss.webrtclibrary.IVideoRoomListener;
import com.clss.webrtclibrary.KurentoSignallingBean;
import com.clss.webrtclibrary.LiveVideoRoom;
import com.clss.webrtclibrary.MediaInfoBean;
import com.clss.webrtclibrary.PlayRecordRoom;
import com.clss.webrtclibrary.ReceiveVideoRoom;
import com.clss.webrtclibrary.SendVideoRoom;
import com.clss.emergencycall.module.webrtcController.WebRtcSignController;
import com.clss.emergencycall.module.webrtcController.WebRtcSignListener;

import org.jetbrains.annotations.NotNull;
import org.webrtc.SurfaceViewRenderer;

/**
 * Activity类的父类
 * Created by TANG hao on 2017/4/12.
 * 1:initBaseRtc
 * 2:startVideo  (进入就播放可以重写 initVideo() 然后调用这个方法)
 */

public abstract class BaseWebRtcActivity extends BaseActivity implements
        BaseView, ServiceConnection, IVideoRoomListener {
    private static final String TAG = "BaseWebRtcActivity";

    public static final int RETRY_CONNECTION_TIME = 5 * 1000;
    public static final int VIDEO_RECORD = 1;//相互直播
    public static final int VIDEO_PLAY = 2;//播放录像
    public static final int VIDEO_JOIN = 3;
    public static final int VIDEO_SEND = 4;//只发送录像

    @NotNull
    public WebRtcSignController mWebRtcSignController;
    public MediaInfoBean mMediaSessionBean;

    public LiveVideoRoom mLiveVideoRoom;
    private PlayRecordRoom mPlayRecordRoom;
    private ReceiveVideoRoom mReceiveVideoRoom;
    private SendVideoRoom mSendVideoRoom;

    public SurfaceViewRenderer mSmallViewRenderer, mTargeViewRenderer;

    public FrameLayout mSmallRenderer;
    public FrameLayout mTargeRenderer;
    public int LIVE_VIDEO_STATUE; // 直播时候的模式：普通，静默，语音报警
    public int VIDEO_TYPE = 1;    // 播放的模式：1：视频直播，2播放录播,3：加入房间，4：录制视频
    public Handler mHandler = new Handler();

    protected void initBaseRtc(FrameLayout mSmallRenderer, FrameLayout mTargeRenderer,
                               MediaInfoBean mMediaSessionBean, int live_video_statue) {
        this.initBaseRtc(mSmallRenderer, mTargeRenderer, mMediaSessionBean, live_video_statue, 1);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    protected void initBaseRtc(FrameLayout mSmallRenderer, FrameLayout mTargeRenderer,
                               MediaInfoBean mMediaSessionBean, int live_video_statue, int videoType) {
        this.mSmallRenderer = mSmallRenderer;
        this.mTargeRenderer = mTargeRenderer;
        this.mMediaSessionBean = mMediaSessionBean;
        this.LIVE_VIDEO_STATUE = live_video_statue;
        mSmallViewRenderer = new SurfaceViewRenderer(this);
        mTargeViewRenderer = new SurfaceViewRenderer(this);
        mSmallViewRenderer.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        mTargeViewRenderer.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        if (mSmallRenderer != null)
            mSmallRenderer.addView(mSmallViewRenderer);
        if (mTargeRenderer != null)
            mTargeRenderer.addView(mTargeViewRenderer);
        this.VIDEO_TYPE = videoType;
//        bindService(new Intent(this, XmppService.class), this, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
//        mXmppBinder = (XmppService.XmppBinder) service;
        initVideo();
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }


    public void initVideo() {
        Lg.i(TAG, "---initVideo===" + mMediaSessionBean.toString());
        mWebRtcSignController = new WebRtcSignController(
                this
                ,new WebRtcSignListener() {
            @Override
            public void signLineIsOpened(boolean isReconnection) {
                Lg.i(TAG, "---signLineIsOpened===" + isReconnection);
                switch (VIDEO_TYPE) {
                    case VIDEO_RECORD:
                        //开始直播
                        if (isReconnection && mLiveVideoRoom != null){
                            Lg.i(TAG, "---需要回收视频房间===");
                            runOnUiThread(() -> {
                                mLiveVideoRoom.stopVideo();
                                mLiveVideoRoom = null;
                            });
                        }
                        initPublicVideoRoom();
                        break;
                    case VIDEO_PLAY:
                        //播放录像
                        initPlayRecordRoom();
                        break;
                    case VIDEO_JOIN:
                        initReceiveVideoRoom();
                        break;
                    case VIDEO_SEND:
                        initSendRoom();
                        break;
                    default:
                }
            }

            @Override
            public void signLineIsClosed() {

            }

            @Override
            public void hasRemoteSignInfo(@NotNull KurentoSignallingBean remoteSign) {
                if (mLiveVideoRoom != null) {
                    mLiveVideoRoom.receivedNewSign(remoteSign);
                }
                if (mPlayRecordRoom != null) {
                    try {
                        mPlayRecordRoom.receivedNewSign(remoteSign);
                    }catch (NullPointerException e){
                        showShortToast("失败，请重试！");
                        e.printStackTrace();
                    }
                }
                if (mReceiveVideoRoom != null) {
                    mReceiveVideoRoom.receivedNewSign(remoteSign);
                }
                if (mSendVideoRoom != null) {
                    mSendVideoRoom.receivedNewSign(remoteSign);
                }
            }
        }, mMediaSessionBean);
    }

    private void initPublicVideoRoom() {
        runOnUiThread(() -> {
            mLiveVideoRoom = new LiveVideoRoom(
                    mMediaSessionBean,
                    mTargeViewRenderer,
                    mSmallViewRenderer,
                    LIVE_VIDEO_STATUE,
                    this
            );
        });
    }

    private void initPlayRecordRoom() {
        Lg.i(TAG, "initPlayRecordRoom:SSSSSSSSSSSS " + mMediaSessionBean);
        mPlayRecordRoom = new PlayRecordRoom(
                mMediaSessionBean,
                mTargeViewRenderer, "",
                this
        );
    }

    private void initReceiveVideoRoom() {
        mReceiveVideoRoom = new ReceiveVideoRoom(
                mMediaSessionBean,
                mTargeViewRenderer,
                this
        );
    }

    private void initSendRoom() {
        Lg.i(TAG, "---initSendRoom===");
        mSendVideoRoom = new SendVideoRoom(
                mMediaSessionBean,
                mTargeViewRenderer,
                this
        );
    }


    public void startVideo() {
        mWebRtcSignController.signLineStartWork();
    }


    public void recycleCall() {
        Lg.i(TAG, "---recycleCall===");
        try {
            if (mLiveVideoRoom != null) {
                mLiveVideoRoom.stopVideo();
                mLiveVideoRoom = null;
            }
            if (mReceiveVideoRoom != null) {
                mReceiveVideoRoom.stopVideo();
            }
            if (mPlayRecordRoom != null) {
                mPlayRecordRoom.stopVideo();
            }
            if (mSendVideoRoom != null) {
                mSendVideoRoom.stopVideo();
            }
            if (mWebRtcSignController != null) {
                mWebRtcSignController.disconnectionSignLine();
            }
        } catch (Exception e) {
            Lg.e(TAG, "recycleCall: " + e.getMessage());
        }
    }

    public int switchCamera(){
        if (mSendVideoRoom != null) {
            boolean s = mSendVideoRoom.switchCamera();
            return s ? 1 : 2;
        }else {
            return 0;
        }
    }

    @Override
    public void videoRoomDisconnect() {
        mHandler.postDelayed(() -> {
            recycleCall();
            initVideo();
            startVideo();
        }, RETRY_CONNECTION_TIME);

    }

    @Override
    public void videoError(String s) {

    }

    @Override
    public void playIsOver() {
        Lg.i(TAG, "playIsOver: ");
        showShortToast("播放结束");
        onBackPressed();
    }

    @Override
    public void videoOnStart() {
        Lg.i(TAG, "---videoOnStart===");
        dismissLoadingDialog();
        if (mSendVideoRoom != null) {
            boolean s = mSendVideoRoom.switchCamera();
            if (!s){
                boolean c = mSendVideoRoom.switchCamera();
                if (!c){
                    mSendVideoRoom.switchCamera();
                }
            }
        }
    }

    @Override
    public void videoConnectionState(String s) {
        Lg.i(TAG, "---videoConnectionState===" + s);
        if (s.equals(ConfigAndUtils.FAILED)){
//            mWebRtcSignController.startReconnectVideoTask();
        }
    }

    @Override
    public void remoteVideoIsEnable(String s) {
        Lg.i(TAG, "remoteVideoIsEnable: =====收到web包进入回调===" + s);
    }

    @Override
    public void setVideoDuration(long l, String s, boolean b) {

    }

    @Override
    public void setVideoPosition(long l) {

    }

    /**
     * 对方离开房间
     */
    @Override
    public void leaveRoom() {

    }

    @Override
    public void sendLocalSign(KurentoSignallingBean kurentoSignallingBean) {
        mWebRtcSignController.hasLocalSignMessagge(kurentoSignallingBean);
    }


    @Override
    public void newArrivedRoom(KurentoSignallingBean kurentoSignallingBean) {

    }

    @Override
    public Context getContext() {
        return this;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            recycleCall();
            unbindService(this);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
